package com.wxg.algorithm.chapter06;

public class UnionFindV2 {

    private int[] parent;
    private int   count;

    public UnionFindV2(int count ) {
        parent = new int[count];
        this.count = count;
        for ( int i = 0 ; i < count ; i ++ ){
            parent[i] = i;
        }
    }

    public int find( int p ) {
        if( p >= 0 && p < count) {
            while ( p != parent[p] ){
                p = parent[p];
            }
            return p;
        }else {
            throw new RuntimeException("传入的参数不合法");
        }
    }

    public boolean isConnected( int p , int q ){
        return find(p) == find(q);
    }

    public void union( int p , int q ) {

        int pRoot = find(p);
        int qRoot = find(q);

        if ( pRoot != qRoot ) {
            parent[pRoot] = qRoot;
        }
    }
}
